package com.justonetech.springboot.controller;

import com.justonetech.springboot.entity.CloudFile;
import com.justonetech.springboot.entity.Folder;
import com.justonetech.springboot.entity.User;
import com.justonetech.springboot.service.CloudFileService;
import com.justonetech.springboot.service.FolderService;
import com.justonetech.springboot.service.UserService;
import com.justonetech.springboot.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * Created by admin on 2018/1/12.
 */
@Controller
@RequestMapping(path = "/file")
@Transactional
public class FileController {

    @Autowired
    private FolderService folderService;

    @Autowired
    private CloudFileService cloudFileService;

    @Autowired
    private UserService userService;

    private final String mainPath = "D:/temp/";

    @RequestMapping(path = "/add-folder")
    public String addFolder(Model model, HttpServletRequest request, Long parentId, String folderName) {
        //todo check parent folder
        Folder parent = folderService.findOne(parentId);

        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);
        Folder folder = new Folder();
        folder.setCreateDate(new Date());
        folder.setFolderName(folderName);
        folder.setParentId(parentId);
        folder.setOwnerId(user.getId());
        Folder save = folderService.save(folder);
        folder.setFolderPath(parent.getFolderPath() + "/" + save.getId());
        folderService.save(folder);

        return getFoldersAndFiles(model, request, parentId, null, null);
    }

    @RequestMapping(path = "/delete-folder")
    public String deleteFolder(Model model, HttpServletRequest request, Long id) {
        //todo check permission
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);

        Folder one = folderService.findOne(id);
        // todo search by folderPath
        //find all file
        List<CloudFile> cloudFileByFolder_id = cloudFileService.getCloudFileByFolder_IdAndOwnerId(one.getId(), user.getId());
        for (int i = 0; i < cloudFileByFolder_id.size(); i++) {
            CloudFile cloudFile = cloudFileByFolder_id.get(i);
            deleteFile(model, request, cloudFile.getId());
        }
        //find all folder
        List<Folder> foldersByParentIdAndOwnerId = folderService.getFoldersByParentIdAndOwnerId(id, user.getId());
        for (int i = 0; i < foldersByParentIdAndOwnerId.size(); i++) {
            Folder folder = foldersByParentIdAndOwnerId.get(i);
            String s = deleteFolder(model, request, folder.getId());
        }
        folderService.delete(one);

        File file = new File(mainPath + user.getId() + "/" + one.getId());
        file.delete();

        return getFoldersAndFiles(model, request, one.getParentId(), null, null);
    }

    @RequestMapping(path = "/add-file")
    public String addFile(Model model, MultipartFile file, HttpServletRequest request, Long folderId) throws IOException {

        Folder folder = folderService.findOne(folderId);
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);
        String fileBasePath = mainPath + user.getId() + "/" + folderId + "/";
        File rootPath = new File(fileBasePath);
        if (!rootPath.exists()) {
            rootPath.mkdirs();
        }
        String originalFilename = file.getOriginalFilename();
        String fillSaveName = System.currentTimeMillis() + "_" + originalFilename;
        CloudFile cloudFile = new CloudFile();
        cloudFile.setCreateDate(new Date());
        cloudFile.setFolder(folder);
        cloudFile.setFileSize(file.getSize());
        cloudFile.setFileName(originalFilename);
        cloudFile.setOwnerId(user.getId());
        cloudFile.setSaveName(originalFilename);
        cloudFile.setSavePath(folderId + "/" + fillSaveName);
        cloudFileService.save(cloudFile);

        file.transferTo(new File(fileBasePath + fillSaveName));
//        ModelAndView modelAndView = new ModelAndView();
//        modelAndView.setViewName("/file/folder-file-list");
        return getFoldersAndFiles(model, request, folderId, null, null);
    }

    @RequestMapping(path = "/delete-file")
    public String deleteFile(Model model, HttpServletRequest request, Long id) {
        //todo check delete permission
        CloudFile cloudFile = cloudFileService.findOne(id);
        Folder folder = cloudFile.getFolder();
        Long folderId = null;
        if (folder != null) {
            folderId = folder.getId();
        }
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);
        String fileBasePath = mainPath + user.getId() + "/";
        File file = new File(fileBasePath + cloudFile.getSavePath());
        file.deleteOnExit();
        cloudFileService.delete(cloudFile);

        return getFoldersAndFiles(model, request, folderId, null, null);
    }

    @RequestMapping(path = "/down-load-file")
    public void downLoadFile(HttpServletRequest request, HttpServletResponse response, Long id) throws Exception {
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);

        CloudFile one = cloudFileService.findOne(id);
        File file = new File(mainPath + user.getId() + "/" + one.getSavePath());
        FileUtils.downloadSection(request, response, file.getPath(), one.getFileName());
    }

    @RequestMapping(path = "/search-folders-and-files")
    public String searchFoldersAndFiles(Model model, HttpServletRequest request, String keyword, Integer pageNo, Integer pageSize) {
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);

        Folder rootFolder = folderService.getFolderByOwnerIdAndUserRootFolder(user.getId(), true);
        List<Folder> folders = folderService.getFolderByFolderNameContainsAndOwnerIdAndParentIdIsNot(keyword, user.getId(), 0L);
        List<CloudFile> cloudFiles = cloudFileService.getCloudFileByFileNameContainsAndOwnerId(keyword, user.getId());

        model.addAttribute("folders", folders);
        model.addAttribute("cloudFiles", cloudFiles);
        model.addAttribute("currentFolder", rootFolder);
        model.addAttribute("parentFolder", null);
        model.addAttribute("viewUrl", "/file/get-folders-and-files");
        return "/file/folder-file-list";
    }

    @RequestMapping(path = "/get-folders-and-files")
    public String getFoldersAndFiles(Model model, HttpServletRequest request,
                                     Long folderId, Integer pageNo, Integer pageSize) {
        String remoteUser = request.getRemoteUser();
        User user = userService.findByUsername(remoteUser);

        if (folderId == null || folderId == 0) {
            Folder folderByOwnerIdAndUserRootFolder = folderService.getFolderByOwnerIdAndUserRootFolder(user.getId(), true);
            if (folderByOwnerIdAndUserRootFolder == null) {
                Folder folder = new Folder();
                folder.setOwnerId(user.getId());
                folder.setFolderName("root");
                folder.setCreateDate(new Date());
                folder.setUserRootFolder(true);
                folder.setParentId(0L);
                folderByOwnerIdAndUserRootFolder = folderService.save(folder);
            }
            folderId = folderByOwnerIdAndUserRootFolder.getId();
        }

        List<Folder> folders = folderService.getFoldersByParentIdAndOwnerId(folderId, user.getId());
        Folder currentFolder = folderService.findOne(folderId);

        List<CloudFile> cloudFiles = cloudFileService.getCloudFileByFolder_IdAndOwnerId(folderId, user.getId());

        Folder parentFolder = folderService.findOne(currentFolder.getParentId());

        model.addAttribute("folders", folders);
        model.addAttribute("cloudFiles", cloudFiles);
        model.addAttribute("currentFolder", currentFolder);
        model.addAttribute("parentFolder", parentFolder);
        model.addAttribute("viewUrl", "/file/get-folders-and-files");
        return "/file/folder-file-list";
    }

}
